import React, { useState } from 'react';
import { Table, Button, Space, Avatar, Modal, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, StarOutlined, StarFilled, HolderOutlined, EyeOutlined, EyeInvisibleOutlined, ImportOutlined, DownloadOutlined, CopyOutlined, ReloadOutlined } from '@ant-design/icons';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
  restrictToVerticalAxis,
} from '@dnd-kit/modifiers';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { useWebsites } from '../context/WebsiteContext';
import WebsiteForm from '../components/WebsiteForm';
import WebsiteImporter from '../components/WebsiteImporter';
import { testLocalStorage, exportWebsitesToCode, downloadCodeFile, resetToDefaultData } from '../utils/storage';

// 可排序的行组件
const SortableRow = ({ children, ...props }) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: props['data-row-key'],
  });

  const style = {
    ...props.style,
    transform: CSS.Transform.toString(transform),
    transition,
    ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
  };

  return (
    <tr {...props} ref={setNodeRef} style={style} {...attributes}>
      {React.Children.map(children, (child) => {
        if (child.key === 'sort') {
          return React.cloneElement(child, {
            children: (
              <HolderOutlined
                {...listeners}
                style={{
                  cursor: 'grab',
                  color: '#999',
                  fontSize: '16px',
                }}
              />
            ),
          });
        }
        return child;
      })}
    </tr>
  );
};

const ManagementPage = () => {
  const { websites, currentWebsiteId, addWebsite, updateWebsite, deleteWebsite, setDefault, reorderWebsites, toggleWebsiteStatus } = useWebsites();
  const [modalVisible, setModalVisible] = useState(false);
  const [importerVisible, setImporterVisible] = useState(false);
  const [editingWebsite, setEditingWebsite] = useState(null);
  const [loading, setLoading] = useState(false);

  console.log('ManagementPage - websites数据:', websites);
  console.log('ManagementPage - websites长度:', websites?.length);

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleAdd = () => {
    setEditingWebsite(null);
    setModalVisible(true);
  };

  const handleEdit = (website) => {
    setEditingWebsite(website);
    setModalVisible(true);
  };

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      if (editingWebsite) {
        updateWebsite(editingWebsite.id, values);
        message.success('网站信息更新成功');
      } else {
        addWebsite(values);
        message.success('网站添加成功');
      }
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = (id) => {
    deleteWebsite(id);
    message.success('网站删除成功');
  };

  const handleSetDefault = (id) => {
    setDefault(id);
    message.success('默认网站设置成功');
  };

  const handleToggleStatus = (id, disabled) => {
    toggleWebsiteStatus(id);
    message.success(disabled ? '网站已启用' : '网站已禁用');
  };

  const handleUpdateDefaultConfig = () => {
    try {
      const code = exportWebsitesToCode(websites);
      
      Modal.confirm({
        title: '更新默认配置',
        width: 800,
        content: (
          <div>
            <p style={{ marginBottom: '16px' }}>
              将当前网站列表更新为默认配置。请选择操作方式：
            </p>
            <div style={{ 
              backgroundColor: '#f5f5f5', 
              padding: '12px', 
              borderRadius: '4px',
              maxHeight: '300px',
              overflow: 'auto',
              fontSize: '12px',
              fontFamily: 'monospace',
              marginBottom: '16px'
            }}>
              <pre>{code}</pre>
            </div>
            <div style={{ backgroundColor: '#e6f7ff', padding: '12px', borderRadius: '4px', marginBottom: '16px', border: '1px solid #91d5ff' }}>
              <p style={{ margin: 0, fontSize: '14px', color: '#0050b3' }}>
                <strong>💡 提示：</strong>此功能将当前的网站配置保存为新的默认配置，新用户首次使用时将看到这些网站。
              </p>
            </div>
            <p style={{ color: '#666', fontSize: '14px', marginBottom: '8px' }}>
              <strong>操作步骤：</strong>
            </p>
            <ol style={{ paddingLeft: '20px', lineHeight: '1.6', fontSize: '14px', color: '#666' }}>
              <li>点击"复制代码"将代码复制到剪贴板（或点击"下载文件"下载代码文件）</li>
              <li>打开 <code>src/utils/storage.js</code> 文件</li>
              <li>找到 <code>defaultWebsites</code> 数组定义（约第3行）</li>
              <li>将复制的代码替换原有的 <code>defaultWebsites</code> 定义</li>
              <li>建议更新 <code>CURRENT_VERSION</code> 版本号（如 '1.6'），这样会重置所有用户的配置</li>
              <li>保存文件并重启应用</li>
            </ol>
          </div>
        ),
        okText: '复制代码',
        cancelText: '下载文件',
        onOk() {
          navigator.clipboard.writeText(code).then(() => {
            message.success('代码已复制到剪贴板，请按步骤更新 storage.js 文件');
          }).catch(() => {
            message.error('复制失败，请手动复制代码');
          });
        },
        onCancel() {
          downloadCodeFile(websites, 'defaultWebsites.js');
          message.success('代码文件已下载，请将内容复制到 storage.js 文件中');
        },
      });
    } catch (error) {
      message.error('生成配置代码失败');
      console.error('生成配置代码失败:', error);
    }
  };

  const handleResetToDefault = () => {
    Modal.confirm({
      title: '重置为默认数据',
      content: (
        <div>
          <p style={{ marginBottom: '16px' }}>
            确定要重置为默认的网站列表吗？
          </p>
          <div style={{ backgroundColor: '#fff2e8', padding: '12px', borderRadius: '4px', border: '1px solid #ffb366' }}>
            <p style={{ margin: 0, fontSize: '14px', color: '#d46b08' }}>
              <strong>⚠️ 警告：</strong>此操作将清除所有当前的网站配置，恢复为系统默认的网站列表，且无法撤销。
            </p>
          </div>
        </div>
      ),
      okText: '确定重置',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        try {
          const defaultData = resetToDefaultData();
          // 刷新页面以重新加载数据
          window.location.reload();
        } catch (error) {
          message.error('重置失败，请重试');
          console.error('重置失败:', error);
        }
      },
    });
  };

  const handleImport = (websiteList) => {
    let successCount = 0;
    websiteList.forEach(website => {
      addWebsite(website);
      successCount++;
    });
    
    message.success(`成功导入 ${successCount} 个网站`);
    setImporterVisible(false);
  };

  const handleDragEnd = (event) => {
    const { active, over } = event;

    if (active.id !== over?.id) {
      const oldIndex = websites.findIndex((item) => item.id === active.id);
      const newIndex = websites.findIndex((item) => item.id === over.id);
      
      const newOrder = arrayMove(websites, oldIndex, newIndex);
      reorderWebsites(newOrder);
      message.success('排序已更新');
    }
  };

  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 60,
      className: 'drag-visible',
      render: () => null, // 内容将在SortableRow中处理
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 80,
      render: (icon, record) => (
        <Avatar 
          src={icon} 
          size={24} 
          style={{ backgroundColor: '#f0f0f0' }}
        >
          {record.name.charAt(0)}
        </Avatar>
      ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <span style={{ 
          opacity: record.disabled ? 0.5 : 1,
          textDecoration: record.disabled ? 'line-through' : 'none'
        }}>
          <strong>{text}</strong>
          {record.disabled && <span style={{ color: '#999', marginLeft: '8px' }}>(已禁用)</span>}
        </span>
      ),
    },
    {
      title: '网站地址',
      dataIndex: 'url',
      key: 'url',
      render: (url) => (
        <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#1890ff' }}>
          {url.length > 40 ? `${url.substring(0, 40)}...` : url}
        </a>
      ),
    },
    {
      title: '搜索地址',
      dataIndex: 'searchUrl',
      key: 'searchUrl',
      render: (searchUrl) => (
        <span style={{ color: '#666' }}>
          {searchUrl.length > 50 ? `${searchUrl.substring(0, 50)}...` : searchUrl}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      render: (_, record) => (
        <Space>
          <Button
            icon={record.disabled ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            type={record.disabled ? 'default' : 'primary'}
            onClick={() => handleToggleStatus(record.id, record.disabled)}
            size="small"
            style={{ 
              backgroundColor: record.disabled ? '#52c41a' : '#ff4d4f',
              borderColor: record.disabled ? '#52c41a' : '#ff4d4f',
              color: record.disabled ? '#fff' : '#fff'
            }}
          >
            {record.disabled ? '启用' : '禁用'}
          </Button>
          <Button
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个网站吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              icon={<DeleteOutlined />}
              danger
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            icon={currentWebsiteId === record.id ? <StarFilled /> : <StarOutlined />}
            type={currentWebsiteId === record.id ? 'primary' : 'default'}
            onClick={() => handleSetDefault(record.id)}
            size="small"
            disabled={record.disabled}
          >
            {currentWebsiteId === record.id ? '已默认' : '设为默认'}
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <h2 style={{ margin: 0 }}>影视网站管理</h2>
          <p style={{ margin: '4px 0 0 0', color: '#666', fontSize: '14px' }}>
            拖拽 <HolderOutlined style={{ color: '#999' }} /> 图标可调整网站显示顺序
          </p>
          <p style={{ margin: '4px 0 0 0', color: '#999', fontSize: '12px' }}>
            共 {websites.length} 个网站，
            启用 {websites.filter(w => !w.disabled).length} 个，
            禁用 {websites.filter(w => w.disabled).length} 个
          </p>
        </div>
        <div style={{ display: 'flex', gap: '12px' }}>
          <Button
            icon={<ReloadOutlined />}
            onClick={handleResetToDefault}
            size="large"
            style={{
              backgroundColor: '#ff4d4f',
              borderColor: '#ff4d4f',
              color: '#fff'
            }}
            title="重置为默认的网站列表"
          >
            重置默认数据
          </Button>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleUpdateDefaultConfig}
            size="large"
            style={{
              backgroundColor: '#52c41a',
              borderColor: '#52c41a',
              color: '#fff'
            }}
            title="将当前网站列表导出为代码，用于更新 storage.js 中的默认配置"
          >
            更新默认配置
          </Button>
          <Button
            onClick={testLocalStorage}
            size="large"
          >
            测试存储
          </Button>
          <Button
            icon={<ImportOutlined />}
            onClick={() => setImporterVisible(true)}
            size="large"
          >
            批量导入
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            size="large"
          >
            添加网站
          </Button>
        </div>
      </div>

      <DndContext
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragEnd={handleDragEnd}
        modifiers={[restrictToVerticalAxis]}
      >
        <SortableContext
          items={websites.map(item => item.id)}
          strategy={verticalListSortingStrategy}
        >
          <Table
            columns={columns}
            dataSource={websites}
            rowKey="id"
            pagination={false}
            components={{
              body: {
                row: SortableRow,
              },
            }}
            rowClassName={(record, index) => {
              const baseClass = index % 2 === 0 ? 'table-row-light' : 'table-row-dark';
              return record.disabled ? `${baseClass} table-row-disabled` : baseClass;
            }}
            style={{
              backgroundColor: '#fff',
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}
          />
        </SortableContext>
      </DndContext>

      <Modal
        title={editingWebsite ? '编辑网站' : '添加网站'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
        destroyOnClose
      >
        <WebsiteForm
          initialValues={editingWebsite}
          onSubmit={handleSubmit}
          onCancel={() => setModalVisible(false)}
          loading={loading}
        />
      </Modal>

      <WebsiteImporter
        visible={importerVisible}
        onCancel={() => setImporterVisible(false)}
        onImport={handleImport}
      />

      <style jsx global>{`
        .table-row-light {
          background-color: #fafafa;
        }
        .table-row-dark {
          background-color: #ffffff;
        }
        .table-row-disabled {
          opacity: 0.6;
          background-color: #f5f5f5 !important;
        }
        .table-row-disabled td {
          background-color: #f5f5f5 !important;
        }
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(-10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        
        .row-dragging {
          background: #fafafa;
          border: 1px solid #1890ff;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          transform: rotate(2deg);
        }
        
        .row-dragging td {
          background: #fafafa;
        }
        
        .drag-visible .anticon {
          cursor: grab;
        }
        
        .drag-visible .anticon:active {
          cursor: grabbing;
        }
        
        .ant-table-tbody > tr:hover .drag-visible .anticon {
          color: #1890ff;
        }
      `}</style>
    </div>
  );
};

export default ManagementPage;